package com.example.ass4;

import java.util.ArrayList;
import java.util.Date;
import data_model.Contact;
import adapter.MyArrayAdapter2;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ReadContactActivity extends ActionBarActivity {
	MyArrayAdapter2 adapter = null;
	ArrayList<Contact> arrList = null;
	ActionMode.Callback callback;
	ActionMode actionMode = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_danhba);
		//===============================================
		TextView tvfont = (TextView) findViewById(R.id.txtdanhba);
		Typeface typeface = Typeface.createFromAsset(getAssets(),
				"fonts/HoboStd.otf");
		tvfont.setTypeface(typeface);
		
		ListView list = (ListView) findViewById(R.id.listItems);
		arrList = new ArrayList<Contact>();
		adapter = new MyArrayAdapter2(this, R.layout.layout_listview, arrList);
		Cursor cursor = getContentResolver().query(
				Uri.parse("content://call_log/calls"), null, null, null, null);
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor
					.getColumnIndex(CallLog.Calls.CACHED_NAME));
			String phoneNumber = cursor.getString(cursor
					.getColumnIndex(CallLog.Calls.NUMBER));
			String duration = cursor.getString(cursor
					.getColumnIndex(CallLog.Calls.DURATION));
			String date = cursor.getString(cursor
					.getColumnIndex(CallLog.Calls.DATE));
			String type = cursor.getString(cursor
					.getColumnIndex(CallLog.Calls.TYPE));
			String direction = null;
			switch (Integer.parseInt(type)) {
			case CallLog.Calls.OUTGOING_TYPE:
				direction = "OUTGOING";
				break;

			case CallLog.Calls.INCOMING_TYPE:
				direction = "INCOMING";
				break;

			case CallLog.Calls.MISSED_TYPE:
				direction = "MISSED";
				break;
			}
			Contact contact = new Contact(name, phoneNumber, "date: "
					+ new Date(Long.valueOf(date)) + " duration:" + duration
					+ "type:" + direction);
			arrList.add(contact);
		}
		cursor.close();
		list.setAdapter(adapter);
		//=============================================
		callback = new ActionMode.Callback() {

			@Override
			public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
				// TODO Auto-generated method stub
				return false;
			}

			@Override
			public void onDestroyActionMode(ActionMode mode) {
				// TODO Auto-generated method stub

			}

			@Override
			public boolean onCreateActionMode(ActionMode mode, Menu menu) {
				// TODO Auto-generated method stub
				getMenuInflater().inflate(R.menu.context_menu, menu);
				return true;
			}

			@Override
			public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
				// TODO Auto-generated method stub
				switch (item.getItemId()) {
				case R.id.remove:
					remove();
					break;
				}
				return true;
			}

		};
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.my_actionbar_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.call:
			return true;
		case R.id.danhba:
			Intent intent = new Intent(ReadContactActivity.this,
					DanhbaActivity.class);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}

	}
	public  boolean deleteContact(ReadContactActivity ctx, String phone, String name) {
	    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
	    Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
	    try {
	        if (cur.moveToFirst()) {
	            do {
	                if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
	                    String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
	                    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
	                    ctx.getContentResolver().delete(uri, null, null);
	                    return true;
	                }

	            } while (cur.moveToNext());
	        }

	    } catch (Exception e) {
	        System.out.println(e.getStackTrace());
	    }
	    return false;
	}
	public void remove() {
		ArrayList<Contact> arrCopy = (ArrayList<Contact>) arrList.clone();
		for (Contact aGoods : arrCopy) {
			if (aGoods.isCheck()) {
				if(deleteContact(ReadContactActivity.this, aGoods.getNumber(), aGoods.getName()))
					arrList.remove(aGoods);
			}
		}
		adapter.notifyDataSetChanged();
		stopMenu();
	}

	public void startMenu() {
		if (actionMode == null) {
			actionMode = startActionMode(callback);
		}
	}

	public void stopMenu() {
		if (actionMode != null) {
			actionMode.finish();
			actionMode = null;
		}
	}
}
